package com.sdsy.blockchaintrainingback.service.training;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sdsy.blockchaintrainingback.context.ThreadLocalContextHolder;
import com.sdsy.blockchaintrainingback.mapper.training.TrainingMapper;
import com.sdsy.blockchaintrainingback.mapper.training.UserTrainingRelationMapper;
import com.sdsy.blockchaintrainingback.pojo.training.Training;
import com.sdsy.blockchaintrainingback.pojo.training.UserTrainingRelation;
import com.sdsy.blockchaintrainingback.vo.training.TrainingRespVo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description TODO
 * @Author linzili
 * @Date 2023/9/27 22:43
 * @Version 1.0
 */
@Service
@Transactional
public class TrainingServiceImpl implements TrainingService {

    @Resource
    private TrainingMapper trainingMapper;

    @Resource
    private UserTrainingRelationMapper userTrainingRelationMapper;

    @Override
    public List<TrainingRespVo> list(String name) {
        List<Training> trainings;
        LambdaQueryWrapper<Training> wrapper = new LambdaQueryWrapper<Training>();
        if (name != null) {
            wrapper.like(Training::getName, name);
        }
        if (ThreadLocalContextHolder.getUserId() == 1) {
            trainings = trainingMapper.selectList(wrapper);
        } else {
            List<UserTrainingRelation> userTrainingRelations = userTrainingRelationMapper.selectList(UserTrainingRelation::getUserId, ThreadLocalContextHolder.getUserId());
            List<Integer> collect = userTrainingRelations.stream().map(UserTrainingRelation::getTrainingId).toList();
            wrapper.in(Training::getTrainingId, collect);
            trainings = trainingMapper.selectList(wrapper);
        }
        List<TrainingRespVo> list = new ArrayList<>();
        for (Training training : trainings) {
            TrainingRespVo trainingRespVo = new TrainingRespVo();
            BeanUtil.copyProperties(training, trainingRespVo);
            list.add(trainingRespVo);
        }
        return list;
    }
}
